package com.example.controller;

import javax.validation.Valid;

import org.hibernate.tool.schema.internal.exec.GenerationTarget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.bean.Girl;
import com.example.bean.Result;
import com.example.dao.GirlRespository;
import com.example.enums.CodeEnum;
import com.example.service.GirlService;
import com.example.utils.ResultUtil;

@RestController
public class GirlController {

	@Autowired
	private GirlRespository girlRespository;
	@Autowired
	private GirlService girlService;

	@GetMapping("/findGirlByid/{id}")
	public Object findGirlByid(@PathVariable("id") Integer id) {
		//return girlRespository.findById(id);
		return ResultUtil.success(girlRespository.findById(id));
	}

	/**
	 * @param girl
	 * @param bindingResult 如果有校验@Valid 就必须用到这个参数
	 * @return
	 */
	@PostMapping("/Girl")
	public Girl createGirl(@Valid Girl girl, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			System.out.println(bindingResult.getFieldError().getDefaultMessage());
			return null;
		}

		return girlRespository.save(girl);
	}

	/**
	 * 
	 * 统一处理返回结果 包含成功和失败
	 * @param girl
	 * @param bindingResult 如果有校验@Valid 就必须用到这个参数
	 * @return
	 */
	@PostMapping("/GirlPost")
	public Object createGirl2(@Valid Girl girl, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultUtil.error(CodeEnum.ERRO_US.getCode(), bindingResult.getFieldError().getDefaultMessage());
		}
		return ResultUtil.success(girlRespository.save(girl));
	}

	/**
	 * 测试事务
	 */
	@GetMapping("/create2Gril")
	public void create2Gril() {
		girlService.createTwoGirl();
	}

	/**
	 * 测试统一异常处理
	 * @param id
	 * @return
	 */
	@GetMapping("/getAge/{id}")
	public Result<Girl> getAge(@PathVariable("id") Integer id )throws Exception {
		return ResultUtil.success(girlService.getAge(id));
	}
}
